package com.example.Dao;

import com.example.pojo.News;
import com.example.pojo.User;
import com.example.utils.ConnUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private User user;

    // ===================== 新增方法1：根据账号查询用户（用于找回密码校验）=====================
    public User getUserByUserId(int userId) {
        User user = null;
        Connection conn = ConnUtils.getConn();
        // SQL：根据账号查询用户（账号是唯一的，查一条）
        String sql = "select * from user where userId = ?";
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setInt(1, userId); // 传入账号（int类型）
            ResultSet rs = pst.executeQuery();
            // 若查询到结果，封装成User对象
            if (rs.next()) {
                user = new User(
                        rs.getInt("userId"),       // 账号
                        rs.getString("userPwd"),    // 密码
                        rs.getString("userPhone"),  // 绑定的手机号（关键，用于匹配）
                        rs.getString("userAuator") ,
                        rs.getString("role")// 权限
                );
            }
        } catch (SQLException e) {
            throw new RuntimeException(e); // 抛出异常，让Service层捕获
        } finally {
            ConnUtils.closeConnection(conn); // 关闭连接
        }
        return user; // 若返回null，说明账号不存在
    }


    // ===================== 新增方法2：修改用户密码（找回密码成功后执行）=====================
    public int updateUserPwd(int userId, String newPwd) {
        int flag = 0; // 影响行数：1=修改成功，0=修改失败
        Connection conn = ConnUtils.getConn();
        // SQL：根据账号修改密码
        String sql = "update user set userPwd = ? where userId = ?";
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1, newPwd); // 新密码
            pst.setInt(2, userId);    // 要修改的账号
            flag = pst.executeUpdate(); // 执行更新，返回影响行数
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            ConnUtils.closeConnection(conn); // 关闭连接
        }
        return flag;
    }

    //登录验证---查询操作
    public User getUser(User user){
        // 首先进行参数验证
        if (user == null) {
            throw new IllegalArgumentException("入参User对象不能为空！");
        }
        if (user.getUserId() == 0) {
            throw new IllegalArgumentException("用户ID不能为空！");
        }
        if (user.getUserPwd() == null || user.getUserPwd().trim().isEmpty()) {
            throw new IllegalArgumentException("用户密码不能为空！");
        }
        if (user.getRole() == null || user.getRole().trim().isEmpty()) {
            throw new IllegalArgumentException("用户角色不能为空！");
        }
        User u=null;
        // 1--->连接数据库
        Connection conn = null;
        PreparedStatement pst = null; // 提升作用域，方便finally关闭
        ResultSet rs = null;
        String sql="select * from user where userId = ? and userPwd = ? and role = ?";
        try {
            conn = ConnUtils.getConn();
             pst =conn.prepareStatement(sql);
            pst.setInt(1, user.getUserId());
            pst.setString(2,user.getUserPwd().trim());
            pst.setString(3,user.getRole().trim());
//            if (user == null) {
//                throw new RuntimeException("入参User对象不能为空！");
//            }
             rs=pst.executeQuery();
            if(rs.next()){
                u=new User(rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (rs != null) {
                try { rs.close(); } catch (SQLException e) { /* 记录日志 */ }
            }
            if (pst != null) {
                try { pst.close(); } catch (SQLException e) { /* 记录日志 */ }
            }
            ConnUtils.closeConnection(conn);
        }
        return u;
    }
    //统计总行数
    public int getTotal(){
        int flag=0;
        Connection conn=ConnUtils.getConn();
        String sql="select count(*) from user";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            ResultSet rs= pst.executeQuery();
            if(rs.next()){
                flag=rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return flag;
    }

    //管理用户
    public List<User> getAllUser(int currentPage, int pageSize) {
        List<User> list = new ArrayList<>();
        Connection conn = ConnUtils.getConn();
        String sql="select * from user limit ?,?";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setInt(1,(currentPage-1)*pageSize);
            pst.setInt(2,pageSize);
            java.sql.ResultSet rs= pst.executeQuery();
            while (rs.next()){
                User n=new User(rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5));
                list.add(n);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return list;
    }
    //添加用户
    public int addUser(User user){
        int flag=0;
        //连接数据库
        Connection conn= ConnUtils.getConn();
        //编写SQL语句
        String sql="insert into user(userId,userPwd,userPhone,userAuator)"+"values(?,?,?,?)";
        //PreparedStatement
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setInt(1,user.getUserId());
            pst.setString(2, user.getUserPwd());
            pst.setString(3, user.getUserPhone());
            pst.setString(4, user.getUserAuator());
            flag=pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        //执行
        return flag;
    }
    //删除用户
    public int deleteUser(int userId){
        int flag=0;
        Connection conn=ConnUtils.getConn();
        String sql="delete from user where userId=?";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setInt(1, userId);
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return flag;
    }
    //批量删除
    public  int deleteBatchUser(List<Integer> ids){
        int flag=0;
        Connection conn=ConnUtils.getConn();
        //自动提交关闭(保持一致性----事务处理)
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        StringBuffer sbuffer=new StringBuffer();//可变长的字符串
        for(int i=0;i<ids.size();i++){
            sbuffer.append("?");  //0?,1?,2?
            if(i<ids.size()-1){
                sbuffer.append(",");
            }
        }
        String sql="delete from user where userId in ("+sbuffer.toString()+")";
        System.out.println(sql);
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            for(int i=0;i< ids.size();i++){
                pst.setInt(i+1,ids.get(i));
            }
            flag= pst.executeUpdate();

//           int rs[]= pst.executeBatch();
//            for(int i=0;i<rs.length;i++){
//                flag+=rs[i];
//            }
            if(flag>0){
                //手动提交
                conn.commit();
            }
        } catch (SQLException e) {
            //回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return flag;
    }

    //编辑用户
    public int EditUser(User user){
        int flag=0;
        //连接数据库
        Connection conn= ConnUtils.getConn();
        //编写SQL语句
        String sql="update user set userPwd=?, userPhone=?, userAuator=? where userId=?;";
        //PreparedStatement
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setString(1, user.getUserPwd());
            pst.setString(2, user.getUserPhone());
            pst.setString(3, user.getUserAuator());
            pst.setInt(4,user.getUserId());
            flag=pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        //执行
        return flag;
    }
    //看用户
    public User getUserInfo(int userId){
        User n=null;
        Connection conn=ConnUtils.getConn();
        String sql="select * from user where userId=?";
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setInt(1,userId);
            ResultSet rs= pst.executeQuery();
            if(rs.next()){
                n=new User(rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5));
            }
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            ConnUtils.closeConnection(conn);
        }
        return n;
    }

}
